import QtQuick 2.14
import QtQuick.Window 2.0
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.14
import Qt.labs.platform 1.1
import QtGraphicalEffects 1.14
Window {
    visible: true
    width: 1180
    height: 770
    minimumWidth: 1050
    minimumHeight: 680
    color: "#232324"

    title: qsTr("图片浏览器")

    // 放置参数：
    property var groupBoxBackColor: "#3A3A3A"           // 右边信息框的背景色
    property var groupBoxFontColor: "#D7D7D7"           // 右边信息框的文字颜色
    property var groupBoxFontSize: 14                   // 右边信息框的文字大小

    // 打开文件的参数
    property string picturesLocation : "";
    property var imageNameFilters : ["所有图片格式 (*.png; *.jpg; *.bmp; *.gif; *.jpeg)"];
    property var pictureList : []
    property var pictureIndex : 0

    // 放大倍数
    property var scaleMax : 800           // 最大800%
    property var scaleMin : 10            // 最小10%

    // 控制缩放命令二维列表
    property var ctrlSliderList : [
        ["放大", scaleMin, scaleMax , photoImage.scale * 100 , "%"],
        ["旋转", -180, 180 , photoImage.rotation, "°"],
    ]

    // GroupBox 的初始化函数
    function initGroupBox(group) {
        group.titleLeftBkColor = "#313131"
        group.titleRightBkColor = "#474951"
        group.titleColor = "#E8E8E8"
        group.contentBkColor = "#2A2A2A"
        group.borderColor = "#454545"
        group.titleFontPixel = 14
        group.radiusVal = 0
        group.borderWidth = 1
    }


    // 列布局，上面是照片和信息，下面是照片浏览小窗口
    ColumnLayout{
        anchors.fill: parent
        spacing: 2

        // 行布局，左是照片，右边是信息
        RowLayout {
            Layout.fillHeight: true
            Layout.fillWidth: true
            spacing: 1

            // 放照片
            Flickable {
                id: flick
                Layout.fillHeight: true
                Layout.fillWidth: true

                MouseArea {                     // 设置滑轮效果
                    anchors.fill: parent
                    onWheel: {
                        // ctrl + 滑轮 则进行旋转图片
                        if (wheel.modifiers & Qt.ControlModifier) {
                            photoImage.rotation += wheel.angleDelta.y / 120 * 5;
                            if (photoImage.rotation > 180)
                                photoImage.rotation =  180
                            else if (photoImage.rotation < -180)
                                photoImage.rotation =  -180
                            if (Math.abs(photoImage.rotation) < 4)  // 如果绝对值小于4°，则摆正图片
                                photoImage.rotation = 0;
                        } else {
                            // 否则不按住 CTRL键， 就是缩放
                            photoImage.scale += photoImage.scale * wheel.angleDelta.y / 120 / 10;
                            if (photoImage.scale > scaleMax / 100)
                                photoImage.scale =  scaleMax / 100
                            else if (photoImage.scale < scaleMin / 100)
                                photoImage.scale =  scaleMin / 100
                        }
                    }
                }

                Image {
                    id: photoImage
                    fillMode: Image.Pad
                    //anchors.centerIn: parent
                    source:  (typeof pictureList[pictureIndex] === 'undefined') ? "" : pictureList[pictureIndex]
                    smooth: true
                    mipmap: true
                    antialiasing: true

                    // 设置位置居中
                    Component.onCompleted: {
                        // pictureList.length = 0
                        x:  parent.width/2-width/2
                        y:  parent.height/2-height/2
                    }

                    // 设置为缩放手势处理：以后代码可以照抄
                    PinchArea {
                        anchors.fill: parent
                        pinch.target: parent
                        pinch.minimumRotation: -180     // 设置拿捏旋转图片最大最小比例
                        pinch.maximumRotation: 180
                        pinch.minimumScale: 0.1         // 设置拿捏缩放图片最小最大比例
                        pinch.maximumScale: 10
                        pinch.dragAxis: Pinch.XAndYAxis
                    }

                    MouseArea {                     // 设置拖动效果
                        anchors.fill: parent
                        drag.target: parent
                        drag.axis: Drag.XAndYAxis

                        // 防止完全把照片拖出去，留20空间：
                        drag.minimumX: 20 - photoImage.width
                        drag.maximumX: flick.width - 20
                        drag.minimumY: 20 - photoImage.height
                        drag.maximumY: flick.height - 20
                    }
                }


            }

            // 放信息框
            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: false

                // 首选宽度
                Layout.preferredWidth : 220
                color: "#313131"
                DynamicGroupBox{
                    id: fileGroup
                    title: "文件选项"
                    width: parent.width

                    // 列布局，放三个按钮：
                    ColumnLayout {
                        anchors.centerIn: parent
                        spacing: 12     // 间隔为12
                        Repeater{
                            // 设置模型
                            model: ListModel{
                                id:fileModel
                                ListElement { name: "打开文件"}
                                ListElement { name: "上一张"}
                                ListElement { name: "下一张"}
                            }
                            // 实际UI模型：
                            DynamicBtn{
                                text: fileModel.get(index).name
                                backColor: groupBoxBackColor
                                fontColor: groupBoxFontColor
                                fontPixelSize: groupBoxFontSize
                                onPressed: {
                                    // console.log("clicked ",fileModel.get(index).name)
                                    fileGroupPressed(index)
                                }
                            }
                        }
                    }
                    Component.onCompleted: initGroupBox(this);
                }
                DynamicGroupBox{
                    id: ctrlGroup
                    title: "图片控制"
                    width: parent.width
                    anchors.top: fileGroup.bottom

                    // 列布局，放俩拖动条。
                    ColumnLayout {
                        anchors.centerIn: parent
                        spacing: 12
                        Repeater {
                            model : 2

                            // 拖动条，两边还有标签。
                            RowLayout {
                                width: parent.width
                                Text {
                                   color: "#D4D4D4"
                                   Layout.fillWidth: false
                                   Layout.preferredWidth : 50
                                   text: ctrlSliderList[index][0]
                                   horizontalAlignment: Text.AlignRight
                                   font.pixelSize: groupBoxFontSize
                                }
                                DynamicSlider {
                                   id: ctrlSlider
                                   Layout.fillWidth: true
                                   Layout.preferredWidth : 130
                                   from: ctrlSliderList[index][1]
                                   value: ctrlSliderList[index][3]
                                   to: ctrlSliderList[index][2]
                                   stepSize: 1
                                   onMoved: setCtrlValue(index, value);
                                }
                                Text {
                                    color: "#D4D4D4"
                                    Layout.fillWidth: false
                                    Layout.preferredWidth : 40
                                    text: parseInt(ctrlSliderList[index][3].toString()) + ctrlSliderList[index][4]
                                }
                            }
                        }
                    }
                    Component.onCompleted: initGroupBox(this);
                }
                DynamicGroupBox{
                    id: imageInfoGroup
                    title: "基本信息"
                    width: parent.width
                    height: 200
                    anchors.top: ctrlGroup.bottom

                    // 列
                    ColumnLayout{
                        width: parent.width
                        spacing: 16
                        Text {
                            color: groupBoxFontColor
                            text: qsTr("尺寸：" + photoImage.sourceSize.width + "x" + photoImage.sourceSize.height)
                            font.pixelSize: groupBoxFontSize
                        }
                        Text {
                            color: groupBoxFontColor
                            text: qsTr("路径：" + ((typeof pictureList[pictureIndex]=== "undefined")?
                                                    "等待打开文件..." :pictureList[pictureIndex].replace("file:///","")))
                            Layout.preferredWidth: parent.width - 20
                            Layout.preferredHeight: 60
                            wrapMode: Text.Wrap
                            font.pixelSize: groupBoxFontSize
                        }
                    }
                    Component.onCompleted: initGroupBox(this)
                }
                DynamicGroupBox{
                    id: authorInfoGroup
                    title: "关于"
                    width: parent.width
                    height: 200
                    anchors.top: imageInfoGroup.bottom
                    ColumnLayout {
                        width: parent.width
                        height: 60
                        Layout.fillHeight : true

                        //spacing: 5
                        Text {
                           id :text1
                           color: groupBoxFontColor
                           text: "原作者: 诺谦"
                           Layout.preferredWidth: parent.width - 20
                           //anchors.top: parent.top
                           wrapMode: Text.Wrap
                           font.pixelSize: 14
                        }
                        Text {
                           id: text2
                           color: groupBoxFontColor
                           text: "本作者: 阿龍1787"
                           //anchors.top: text1.bottom
                           Layout.preferredWidth: parent.width - 20
                           wrapMode: Text.Wrap
                           font.pixelSize: 14
                        }
                        Text {
                            text: "<a href='https://www.alon1787.top'>个人主页：www.alon1787.top</a>"
                            onLinkActivated: {
                                Qt.openUrlExternally(link)
                            }
                        }
                        Text {
                            text: "<a href='https://www.alon1787.top/biji/'>个人学习笔记网站</a>"
                            //textFormat: Text.AutoTextFormat

                            onLinkActivated: {
                                Qt.openUrlExternally(link)
                            }
                        }
                    }
                    Component.onCompleted: initGroupBox(this);
                }
            }
        }

        // 最下面的照片框
        Rectangle {
            id: images
            Behavior on Layout.preferredHeight { NumberAnimation { duration: 250 } }
            Layout.fillHeight: false
            Layout.fillWidth: true
            Layout.preferredHeight: 130

            // 渐变色填充
            LinearGradient {
                anchors.fill: parent
                source: parent
                start: Qt.point(0, 0)
                end: Qt.point(0, parent.height)
                gradient: Gradient {
                    GradientStop { position: 0.0; color: "#484848" }
                    GradientStop { position: 0.01; color: "#373737" }
                    GradientStop { position: 1.0; color: "#2D2D2D" }
                }


            }

            // 收起和展开按钮
            Button {
                id: imageCtrlBtn
                text:  images.Layout.preferredHeight <= 30 ? "展开("+pictureList.length+")" :
                                                             "收起("+pictureList.length+")"
                anchors.right: parent.right
                anchors.rightMargin: 3
                z: 100
                background: Rectangle {
                    color: "transparent"
                }
                contentItem: Label {                    // 设置文本
                    id: btnForeground
                    text: parent.text
                    font.family: "Microsoft Yahei"
                    font.pixelSize: 14
                    color:  imageCtrlBtn.hovered ? "#D7D7D7" : "#AEAEAE"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                onPressed: {
                    if (text.indexOf("收起") >= 0) {
                        images.Layout.preferredHeight = 30
                    } else {
                        images.Layout.preferredHeight = 130
                    }
                }
            }

            // 图片浏览框
            ScrollView {
                  id: imageScroll
                  anchors.fill: parent
                  anchors.leftMargin: 10
                  anchors.rightMargin: 10

                  wheelEnabled: true
                  WheelHandler {
                        onWheel: openNewImageAndUpdateScroll(event.angleDelta.y > 0 ? pictureIndex - 1 : pictureIndex + 1)
                  }

                  ScrollBar.horizontal.policy: ScrollBar.horizontal.size >= 1.0 ?
                                                 ScrollBar.AlwaysOff : ScrollBar.AlwaysOn
                  ScrollBar.vertical.policy: ScrollBar.AlwaysOff

                  ScrollBar.horizontal.contentItem: Rectangle {
                      implicitHeight: 7
                      implicitWidth: 100
                      radius: height / 2
                      color: "#7D7C7C"
                      visible: images.Layout.preferredHeight <= 30 ? false : true
                  }




                  Row {
                      id:imagesRow
                      anchors.fill: parent
                      anchors.topMargin: 30
                      spacing: 20
                      Repeater {
                          model: pictureList.length

                          Button {
                              implicitWidth: 85
                              implicitHeight: 85
                              onPressed: openNewImageAndUpdateScroll(index)
                              background: Rectangle {
                                  color: "#202020"
                                  border.color: pictureIndex == index ? "#2770DF" :
                                                 hovered ? "#6C6A6A" : "transparent"
                                  radius: 5
                                  border.width: 3
                              }
                              Image {
                                  anchors.fill:parent
                                  anchors.margins: 6
                                  antialiasing: true
                                  fillMode: Image.PreserveAspectFit
                                  source: pictureList[index]

                              }
                          }
                      }
                  }
             }
        }
    }


    // 用来控制“文件选项”框三个按钮的功能：
    function fileGroupPressed(index) {
        switch (index) {
            case 0 :  fileDialog.open(); break;
            case 1 :  openNewImageAndUpdateScroll(pictureIndex - 1); break;
            case 2 :  openNewImageAndUpdateScroll(pictureIndex + 1); break;
        }
    }

    // 打开文件对话框
    FileDialog {
        id: fileDialog
        title: "请打开图片(可以多选)"
        fileMode: FileDialog.OpenFiles
        folder: picturesLocation
        nameFilters: imageNameFilters
        onAccepted: {
            pictureList = files
            // openNewImage(0)
        }
        onFolderChanged: picturesLocation = folder
    }

    // 缩放和旋转控制。
    function setCtrlValue(index, value) {
        switch (index) {
            case 0 :  photoImage.scale  = value / 100; break;
            case 1 :  photoImage.rotation = value; break;
        }
    }

    // 可以控制当前照片显示到大照片的函数
    function openNewImageAndUpdateScroll(index) {
        if (index < 0 || index >= pictureList.length) {
            return false
        }
        pictureIndex = index
        photoImage.x = flick.width / 2 - photoImage.width / 2
        photoImage.y = flick.height / 2 - photoImage.height / 2
        photoImage.scale = 1.0
        photoImage.rotation = 0

        var scrollLen = 1.0 - imageScroll.ScrollBar.horizontal.size;
        if (scrollLen > 0) {
            scrollLen =  scrollLen * pictureIndex  / (pictureList.length - 1)
            imageScroll.ScrollBar.horizontal.position = scrollLen
        }
        return true
    }


}
